package com.pcbly.web.components.utils.theme;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListResourceBundle;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Set;

import org.apache.commons.io.FileUtils;

import com.pcbly.web.components.utils.ClassUtilsStatic;

@SuppressWarnings("unchecked")
public class Theme implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7883142513387672206L;
//	private static final String RESOURCE_BUNDLE_NAMES[] = { "office_i18n",
//			"office_custom_i18n", "office_setup", "office_admin" };
	private String name;
	private String description;
	private Properties properties;
	private Map localeRules;
	private Map resourceBundleOverrides;
	private transient Locale locale;

	public static class ThemeResourceBundle extends ListResourceBundle
			implements Serializable {

		/**
		 * 
		 */
		private static final long serialVersionUID = 52235231929534245L;

		public Object[][] getContents() {
			return contents;
		}

		private Object contents[][];

		protected ThemeResourceBundle(Map newKeyValues) {
			contents = new Object[newKeyValues.size()][2];
			int index = 0;
			for (Iterator i$ = newKeyValues.keySet().iterator(); i$.hasNext();) {
				String key = (String) i$.next();
				contents[index][0] = key;
				contents[index][1] = ((String[]) newKeyValues.get(key))[1];
				index++;
			}

		}
	}

	public Theme(String name, String description, Properties properties) {
		this.name = name.toLowerCase();
		this.description = description;
		this.properties = properties;
		readResolve();
	}

	private Object readResolve() {
		if (localeRules == null)
			localeRules = new HashMap();
		resourceBundleOverrides = new HashMap();
		return this;
	}

//	 private ThemeManager getThemeManager() {
//	 return new ThemeManager();
//	 }

	public String getDescription() {
		return description;
	}

	public String getName() {
		return name;
	}

	/**
	 * @deprecated Method getLocale is deprecated
	 */

	public Locale getLocale() {
		return locale;
	}

	public String getProperty(String name) {
		return getProperty(name, null);
	}

	public String getProperty(String name, String defaultValue) {
		if (properties != null)
			return (String) properties.get(name);
		else
			return defaultValue;
	}

	public Set getPropertyNames() {
		if (properties != null)
			return null;
		else
			return Collections.emptySet();
	}

	public int getIntProperty(String name, int defaultValue) {
		String value;
		value = getProperty(name);
		if (value == null)
			return defaultValue;
		try {
			return Integer.parseInt(value);
		} catch (NumberFormatException nfe) {
			return defaultValue;
		}
	}

	public boolean getBooleanProperty(String name) {
		return getBooleanProperty(name, false);
	}

	public boolean getBooleanProperty(String name, boolean defaultValue) {
		String value = getProperty(name);
		if (value != null)
			return Boolean.valueOf(value).booleanValue();
		else
			return defaultValue;
	}

	public boolean validate() {
		boolean validated = true;
		if (name == null)
			validated = false;
		return validated;
	}

	public ResourceBundle getResourceBundleOverride(Locale locale) {
		return (ResourceBundle) resourceBundleOverrides.get(locale);
	}

	public List getResourceBundleRules(Locale locale) {
		return (List) localeRules.get(locale);
	}

	public void setResourceBundleRules(Locale locale, List rules) {
		localeRules.put(locale, rules);
	}

	public String getTemplateSrc(String templateName) throws IOException {
		String templateValue=null;
		BufferedReader reader;
		String templatesHome = (new StringBuilder()).append(File.separator)
				.append(getName()).toString();
		File templateFile = new File((new StringBuilder())
				.append(templatesHome).append(templateName).append(".ftl")
				.toString());
		InputStream stream = ClassUtilsStatic
				.getResourceAsStream((new StringBuilder()).append(templateName)
						.append(".ftl").toString());
		if (stream == null)
			return null;
		stream.close();
		if (templateFile.exists()) {
			templateValue = FileUtils.readFileToString(templateFile, "UTF-8");
		}
		try {
			reader = new BufferedReader(new InputStreamReader(ClassUtilsStatic
					.getResourceAsStream((new StringBuilder()).append(
							templateName).append(".ftl").toString())));
			StringBuffer buf = new StringBuffer();
			String line;
			while ((line = reader.readLine()) != null)
				buf.append(line).append(System.getProperty("line.separator"));
			templateValue = buf.toString();
			if (reader != null)
				reader.close();
		} catch (Exception exception) {

		}
		return templateValue;
	}

//	public void setTemplateSrc(String templateName, String templateSrc)
//			throws IOException {
//		setTemplateSrc(templateName, templateSrc, true);
//	}

//	private void setTemplateSrc(String templateName, String templateSrc,
//			boolean sendClusterTask) throws IOException {
//		String templatesHome = getThemeManager().getThemeHome(this);
//		File templateFile = new File((new StringBuilder())
//				.append(templatesHome).append(templateName).append(".ftl")
//				.toString());
//		boolean exists = templateFile.exists();
//		if (!exists)
//			FileUtils.forceMkdir(templateFile.getParentFile());
//		FileUtils.writeStringToFile(templateFile, templateSrc, "UTF-8");
//		if (!exists)
//			ThemeTemplateLoader.clearCache(getName(), (new StringBuilder())
//					.append(templateName).append(".ftl").toString());
//	}

//	public void loadResourceBundleRulesOverrides() {
//		Locale locale;
//		Map keyValues;
//		for (Iterator i$ = localeRules.keySet().iterator(); i$.hasNext(); resourceBundleOverrides
//				.put(locale, new ThemeResourceBundle(keyValues))) {
//			locale = (Locale) i$.next();
//			List rules = (List) localeRules.get(locale);
//			keyValues = new HashMap();
//			ResourceBundleRule rule;
//			for (Iterator it = rules.iterator(); it.hasNext(); applyRuleToBundles(
//					rule, locale, keyValues))
//				rule = (ResourceBundleRule) it.next();
//
//		}
//
//	}
}
